<template>
    <view class="" @tap="show_recall = false;">
        <!-- 聊天窗口 -->
        <scroll-view :scroll-into-view="scroll_to" scroll-y="true" class="scroll-Y" @click="show_tool = false;">

            <!-- 职位卡片信息 -->
            <view class="card" v-if="job.id" @click="_toView('views/detail/index?id='+job.id)">
                <view class="cardItem">
                    <view class="title mdTitle Han">
                        {{job.title}}
                    </view>
                    <view class="msg Han mdText">
                        <text>{{job.company.rzjd}}</text>
                        <text>{{job.company.gsgm}}</text>
                    </view>

                    <view class="tags mdText Han">
                        <view class="tag">{{job.position}}</view>
                        <view class="tag">{{job.gzjy=='不限' ? '经验不限' : job.gzjy}}</view>
                        <view class="tag">{{job.zgxl=='不限' ? '学历不限' : job.zgxl}}</view>
                    </view>

                    <view class="hr">
                        <image :src="job.company.logo" mode=""></image>
                        <text class="md2Text">{{job.company.shortname || job.company.name}}</text>
                    </view>

                    <text class="salary mdTitle Han">
                        {{job.salary_min}}-{{job.salary_max}}K
                    </text>

                    <!-- 分割线 -->
                    <view class="line">

                    </view>

                    <!-- 时间 -->
                    <view class="editLine">
                        <text
                            class="Han md2Text">{{formatTime(chat.createtime)}}由{{chat.from == 'user' ? '我' : '对方'}}发起的会话</text>
                    </view>
                </view>
            </view>

            <!-- 消息 -->
            <view class="msgList">
                <block v-for="(item, index) in list" :key="index" v-if="item.is_recall != 1">
                    <!-- 时间点 -->
                    <view class="msgTime mgrey md2Text" style="margin: 30rpx auto;padding: 0;"
                        v-if="index == 0 || item.createtime - list[index-1].createtime > 1800">
                        {{formatTime(item.createtime)}}
                    </view>
                    <view :id="'msg-'+item.id" class="msgItem" :class="{forRight:item.send == 'user'}">
                        <view class="other" v-if="item.send != 'user'">
                            <image :src="item.avatar" mode=""></image>
                            <view class="msgText">
                                <text v-if="item.type == 'text'">{{item.msg}}</text>
                                <image style="width: 200rpx;" mode="widthFix" :src="item.msg"
                                    v-if="item.type == 'image'"></image>
                            </view>
                        </view>

                        <view class="self" v-if="item.send == 'user'">
                            <view class="TextArea" @longtap="showRecall(item);">
                                <view class="msgText">
                                    <text v-if="item.type == 'text'">{{item.msg}}</text>
                                    <image style="width: 200rpx;" mode="widthFix" :src="item.msg"
                                        v-if="item.type == 'image'"></image>
                                </view>
                                <view class="isRead mgrey mdText" v-if="item.is_read">
                                    已读
                                </view>

                                <view class="recall" v-if="show_recall == item.id" @tap="recall(item);">撤回</view>
                            </view>
                            <view class="imgArea">
                                <image :src="item.avatar" mode=""></image>
                                <view class="imggap" v-if="item.is_read">

                                </view>
                            </view>
                        </view>
                    </view>
                </block>
            </view>
        </scroll-view>

        <!-- 底部操作栏 -->
        <view class="bar">
            <view class="btns">
                <view class="words md4Text" @click="showCyy">
                    常用语
                </view>
                <!-- <view style="margin-left: 20rpx;flex: 1;background-color: red;">
                    <u-textarea type="text" v-model="msg" border="none" placeholder="请输入…" fontSize="14" autoHeight ></u-textarea>
                </view> -->
                <input type="text" placeholder="请输入…" v-model="msg" class="putIn md8Text" />
                <!-- <textarea  placeholder="请输入…" v-model="msg" style="flex: 1;height: 100rpx;font-size: 28rpx;margin-left: 20rpx;padd"></textarea> -->
                <!-- <view style="flex: 1;margin-left: 10rpx;margin-bottom: 5rpx;">
                    <u--textarea v-model="msg" placeholder="请输入" autoHeight border="none"></u--textarea>
                </view> -->
                <view class="more">
                    <image src="../../../static/imgs/detail/express.png" mode="" @click="show_tool = 'emoji';"></image>
                    <image src="../../../static/imgs/detail/add.png" mode="" v-if="msg==''" @click="show_tool = 'more'">
                    </image>
                    <view class="send md4Text" v-else @click="sendMsg">发送</view>
                </view>
            </view>

            <view class="express" v-show="show_tool == 'emoji'">
                <view class="md4Text all">
                    全部表情
                </view>

                <view class="emojis">
                    <view class="emoji" v-for="(item,index) in emojis" :key="index" @click="addEmoji(item)">
                        {{item}}
                    </view>
                </view>
            </view>

            <view class="addFuncs" v-show="show_tool == 'more'">
                <view class="fun" @click="addImg('camera')">
                    <image src="../../../static/imgs/detail/photo.png" mode=""></image>
                    <view class="name smTitle">
                        拍摄
                    </view>
                </view>

                <view class="fun" @click="addImg('album')">
                    <image src="../../../static/imgs/detail/image.png" mode=""></image>
                    <view class="name smTitle">
                        照片
                    </view>
                </view>
            </view>
        </view>

        <u-action-sheet :actions="cyy_list" title="常用语" description="点击下列常用语,直接发送给对方" :closeOnClickAction="true"
            :safeAreaInsetBottom="true" :closeOnClickOverlay="true" cancelText="取消" :show="show_cyy" @select="sendCyy"
            @close="closeCyy"></u-action-sheet>

        <!-- <u-action-sheet :actions="[{name: '确定'}]" title="是否撤回消息" cancelText="取消" :show="show_recall"
            @close="show_recall = false" @select="recall"></u-action-sheet> -->
    </view>
</template>

<script>
    export default {
        data() {
            return {
                emojis: ["😀", "😁", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎", "😍", "😘", "😗", "😙", "😚", "☺",
                    "😇", "😐", "😑", "😶", "😏", "😣", "😥", "😮", "😯", "😪", "😫", "😴", "😌", "😛", "😜", "😝",
                    "😒", "😓", "😔", "😕", "😲", "😷", "😖", "😞", "😟", "😤", "😢", "😭", "😦", "😧", "😨", "😬",
                    "😰", "😱", "😳", "😵", "😡", "😠", "👦", "👧", "👨", "👩", "👴", "👵", "👶", "👱", "👮", "👲",
                    "👳", "👷", "👸", "💂", "🎅", "👰", "👼", "💆", "💇", "🙍", "🙎", "🙅", "🙆", "💁", "🙋", "🙇",
                    "🙌", "🙏", "👤", "👥", "🚶", "🏃", "👯", "💃", "👫", "👬", "👭", "💏", "💑", "👪", "💪", "👈",
                    "👉", "☝", "👆", "👇", "✌", "✋", "👌", "👍", "👎", "✊", "👊", "👋", "👏", "👐", "✍", "👣", "👀",
                    "👂", "👃", "👅", "👄", "💋", "👓", "👔", "👙", "👛", "👜", "👝", "🎒", "💼", "👞", "👟", "👠",
                    "👡", "👢", "👑", "👒", "🎩", "🎓", "💄", "💅", "💍", "🌂", "📶", "📳", "📴", "♻", "🏧", "🚮",
                    "🚰", "♿", "🚹", "🚺", "🚻", "🚼", "🚾", "⚠", "🚸", "⛔", "🚫", "🚳", "🚭", "🚯", "🚱", "🚷",
                    "🔞", "💈", "🙈", "🐒", "🐶", "🐕", "🐩", "🐺", "🐱", "🐈", "🐯", "🐅", "🐆", "🐴", "🐎", "🐮",
                    "🐂", "🐃", "🐄", "🐷", "🐖", "🐗", "🐽", "🐏", "🐑", "🐐", "🐪", "🐫", "🐘", "🐭", "🐁", "🐀",
                    "🐹", "🐰", "🐇", "🐻", "🐨", "🐼", "🐾", "🐔", "🐓", "🐣", "🐤", "🐥", "🐦", "🐧", "🐸", "🐊",
                    "🐢", "🐍", "🐲", "🐉", "🐳", "🐋", "🐬", "🐟", "🐠", "🐡", "🐙", "🐚", "🐌", "🐛", "🐜", "🐝",
                    "🐞", "🦋", "💐", "🌸", "💮", "🌹", "🌺", "🌻", "🌼", "🌷", "🌱", "🌲", "🌳", "🌴", "🌵", "🌾",
                    "🌿", "🍀", "🍁", "🍂", "🍃", "🌍", "🌎", "🌏", "🌐", "🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗",
                    "🌘", "🌙", "🌚", "🌛", "🌜", "☀", "🌝", "🌞", "⭐", "🌟", "🌠", "☁", "⛅", "☔", "⚡", "❄", "🔥",
                    "💧", "🌊", "🏀", "🏈", "🏉", "🎾", "🎱", "🎳", "⛳", "🎣", "🎽", "🎿", "😈", "👿", "👹", "👺",
                    "💀", "☠", "👻", "👽", "👾", "💣", "🌋", "🗻", "🏠", "🏡", "🏢", "🏣", "🏤", "🏥", "🏦", "🏨",
                    "⛲", "🌁", "🌃", "🌆", "🌇", "🎠", "🎡", "🎢", "🚂", "🚌", "🚍", "🚎", "🚏", "🚐", "🚑", "🚒",
                    "🚓", "🚔", "🚕", "🚖", "🚗", "🚘", "💌", "💎", "🔪", "💈", "🚪", "🚽", "🚿", "🛁", "⌛", "⏳",
                    "⌚", "⏰", "🎈", "🎉", "💤", "💢", "💬", "💭", "♨", "🌀", "🔔", "🔕", "✡", "✝", "🔯", "📛", "🔰",
                    "🔱", "⭕", "✅", "☑", "✔", "✖", "❌", "❎", "➕", "➖", "➗", "➰", "➿", "〽", "✳", "✴", "❇", "‼", "⁉",
                    "❓", "❔", "❕", "❗", "🕛", "🕧", "🕐", "🕜", "🕑", "🕝", "🕒", "🕞", "🕓", "🕟", "🕔", "🕠",
                    "🕕", "🕡", "🕖", "🕢", "🕗", "🕣", "🕘", "🕤", "🕙", "🕥", "🕚", "🕦", "⏱", "⏲", "🕰", "💘",
                    "❤", "💓", "💔", "💕", "💖", "💗", "💙", "💚", "💛", "💜", "💝", "💞", "💟❣", "🍇", "🍈", "🍉",
                    "🍊", "🍋", "🍌", "🍍", "🍎", "🍏", "🍐", "🍑", "🍒", "🍓"
                ],
                show_tool: false,

                id: 0,

                list: [],
                scroll_to: '',
                chat: {},
                job: {},
                cyy_list: [],
                show_cyy: false,

                msg: '',

                ws: false,
                ws_timer: false,

                user: {},

                show_recall: false,
                recall_msg: {}
            };
        },
        onLoad(options) {
            this.id = options.id || 0;
            this.user = uni.getStorageSync('user') || {};
            this.getChatDetail();
        },
        onShow() {
            this.wsConnect();
        },
        onNavigationBarButtonTap(e) {
            uni.navigateTo({
                url: '/pages/views/detail/complaint?job_id=' + this.job.id
            });
        },
        onUnload() {
            if (this.ws && this.ws.readyState === 1) {
                this.ws.close();
            }
        },
        methods: {
            showRecall(e) {
                this.recall_msg = e;
                this.show_recall = e.id;
            },
            recall(e) {
                this.wsSend({
                    event: 'chat_recall',
                    chat_id: this.recall_msg.chat_id,
                    chat_msg_id: this.recall_msg.id
                });
                this.show_recall = false;
            },
            getChatDetail() {
                this._ajax({
                    url: '/api/user/getChatDetail',
                    data: {
                        id: this.id
                    },
                    success: res => {
                        if (res.code == 1) {
                            this.chat = res.data.chat;
                            this.job = res.data.job;
                            this.list = res.data.list;
                            uni.setNavigationBarTitle({
                                title: this.job.company.name
                            })
                            var cyy_list = [];
                            for (var i in res.data.cyy_list) {
                                cyy_list.push({
                                    name: res.data.cyy_list[i]
                                });
                            }
                            this.cyy_list = cyy_list;

                            if (this.list.length > 0) {
                                setTimeout(() => {
                                    this.scroll_to = 'msg-' + this.list[this.list.length - 1].id;

                                    this.wsSend({
                                        event: 'chat_read',
                                        chat_id: this.chat.id,
                                        chat_msg_id: '*',
                                        reader: 'user'
                                    });
                                }, 200);

                            }
                        } else {
                            this._toast(res.msg);
                        }
                    }
                }, 1);
            },

            formatTime(time) {
                var date = new Date(time * 1000),
                    str = '';
                if (date.getFullYear() != new Date().getFullYear()) {
                    str += date.getFullYear() + '-';
                } else if (date.getMonth() != new Date().getMonth() || date.getDate() != new Date().getDate()) {
                    str += (date.getMonth() + 1) + '-' + date.getDate() + ' ';
                }
                str += date.getHours() + ':' + ('0' + date.getMinutes()).slice(-2);
                return str;
            },
            showCyy() {
                this.show_cyy = true;
            },
            sendCyy(e) {
                console.log(JSON.stringify(e))
                this.wsSend({
                    chat_id: this.chat.id,
                    company_id: this.chat.company_id,
                    user_id: this.chat.user_id,
                    event: 'chat_msg',
                    type: 'text',
                    send: 'user',
                    msg: e.name
                });
            },
            closeCyy() {
                this.show_cyy = false;
            },
            addEmoji(v) {
                console.log(v);
                this.msg += v;
            },
            addImg(type) {
                uni.chooseImage({
                    count: 1,
                    sourceType: [type],
                    success: res => {
                        this._upload({
                            url: '/api/common/upload',
                            filePath: res.tempFilePaths[0],
                            success: res => {
                                if (res.code == 1) {
                                    this.wsSend({
                                        chat_id: this.chat.id,
                                        company_id: this.chat.company_id,
                                        user_id: this.chat.user_id,
                                        event: 'chat_msg',
                                        type: 'image',
                                        send: 'user',
                                        msg: res.data.url
                                    });
                                } else {
                                    this._toast(res.msg);
                                }
                            }
                        });
                    }
                })
            },
            sendMsg() {
                if (!this.msg.trim()) {
                    return this._toast('发送消息不能为空');
                }
                this.wsSend({
                    chat_id: this.chat.id,
                    company_id: this.chat.company_id,
                    user_id: this.chat.user_id,
                    event: 'chat_msg',
                    type: 'text',
                    send: 'user',
                    msg: this.msg
                });
                this.msg = '';
                this.show_tool = false;
            },
            wsConnect() {
                if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) {
                    return;
                }
                // this.ws = new WebSocket(this._ws_host);
                console.log(this._ws_host);
                this.ws = uni.connectSocket({
                    url: this._ws_host,
                    success: res => {},
                    error: res => {
                        this._toast('连接失败');
                    }
                });

                this.ws.onOpen((e) => {
                    console.log("连接成功", e);
                    console.log(this.ws);
                    this.wsSend({
                        event: 'login',
                        user_id: this.user.id
                    });
                    if (this.ws_timer) {
                        clearInterval(this.ws_timer);
                    }
                    this.ws_timer = setInterval(() => {
                        this.wsSend({
                            event: 'keep'
                        });
                    }, 1000 * 10);
                });

                this.ws.onMessage((e) => {
                    console.log("收到服务端的消息：", e.data);
                    if (e.data) {
                        this.wsMsg(JSON.parse(e.data));
                    }
                });

                this.ws.onClose((e) => {
                    console.log("连接关闭", e);
                    clearInterval(this.ws_timer);
                });

                this.ws.onError((e) => {
                    console.log("连接出错", e);
                });
            },
            wsSend(data) {
                data = JSON.stringify(data);
                console.log('向服务端发送消息', data);
                if (this.ws.readyState === 0) {
                    setTimeout(() => {
                        this.ws.send({
                            data: data
                        });
                    }, 1000);
                } else if (this.ws.readyState === 1) {
                    this.ws.send({
                        data: data
                    });
                } else {
                    // this._toast('聊天服务器已断开连接');
                }
            },
            wsMsg(res) {
                switch (res.event) {
                    case 'login':
                        if (res.code !== 1) {
                            this._toast(res.msg);
                        }
                        break;
                    case 'logout':
                        this.ws.close();
                        // this._toast(res.msg);
                        break;
                    case 'chat_msg':
                        if (res.code == 1) {
                            if (this.id == res.data.chat_id) {
                                this.list.push(res.data);
                                if (res.data.send != 'user') {
                                    this.wsSend({
                                        event: 'chat_read',
                                        chat_id: res.data.chat_id,
                                        chat_msg_id: res.data.id,
                                        reader: 'user'
                                    });
                                }
                                setTimeout(() => {
                                    this.scroll_to = 'msg-' + res.data.id;
                                }, 200);
                            }
                        } else {
                            this._toast(res.msg);
                        }
                        break;
                    case 'chat_read':
                        if (res.code == 1) {
                            console.log(res.data);
                            if (this.id == res.data.chat_id) {
                                for (var i in this.list) {
                                    if (this.list[i].send != res.data.reader && (res.data.chat_msg_id === '*' || res
                                            .data.chat_msg_id == this.list[i].id)) {
                                        this.list[i].is_read = 1;
                                    }
                                }
                            }
                        }
                        break;
                    case 'chat_recall':
                        if (res.code == 1) {
                            console.log(res.data);
                            if (this.id == res.data.chat_id) {
                                for (var i in this.list) {
                                    if (res.data.chat_msg_id == this.list[i].id) {
                                        this.list[i].is_recall = 1;
                                    }
                                }
                            }
                        } else {
                            this._toast(res.msg);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    };
</script>

<style scoped lang="less">
    .scroll-Y {
        width: 100%;
        height: 100vh;
        background-color: #f9f9f9;
        padding-bottom: 116upx;

        .msgTime {
            width: 100%;
            text-align: center;
            padding-top: 60upx;
        }

        .card {
            width: 682upx;
            margin: 20upx auto;
        }

        .msgList {
            width: 682upx;
            margin: 10upx auto;

            .forRight {
                text-align: right;
            }

            .msgItem {
                margin-bottom: 40upx;

                .other {
                    display: flex;
                    align-items: flex-start;

                    // align-items: center;

                    image {
                        width: 80upx;
                        height: 80upx;
                        border-radius: 50%;
                    }

                    .msgText {
                        max-width: 448upx;
                        margin-left: 32upx;
                        background: #ffffff;
                        opacity: 1;
                        line-height: 40upx;
                        border-radius: 16upx;
                        padding: 15upx;
                        word-break: break-all;
                        white-space: pre-line;
                    }
                }

                .self {
                    display: flex;
                    justify-content: flex-end;
                    align-items: flex-start;


                    .imgArea {
                        display: inline-block;

                        image {
                            width: 80upx;
                            height: 80upx;
                            border-radius: 50%;
                        }

                        .imggap {
                            height: 32upx;
                        }
                    }


                    .TextArea {
                        display: inline-block;
                        max-width: 450rpx;
                        position: relative;

                        .msgText {
                            max-width: 450rpx;
                            margin-right: 30rpx;
                            background: #3f6bb0;
                            color: #ffffff;
                            opacity: 1;
                            line-height: 40upx;
                            border-radius: 16upx;
                            padding: 15upx;
                            text-align: left;
                            word-break: break-all;
                            white-space: pre-line;
                        }

                        .isRead {
                            text-align: right;
                            margin-right: 30rpx;
                            padding-top: 10upx;
                        }

                        .recall {
                            position: absolute;
                            width: 100rpx;
                            height: 50rpx;
                            top: -60rpx;
                            right: 30rpx;
                            // left: 50%;
                            // margin-left: -65rpx;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            background-color: #060607;
                            color: #fff;
                            z-index: 9;
                            border-radius: 10rpx;
                            font-size: 24rpx;
                        }

                        .recall::after {
                            content: "";
                            position: absolute;
                            width: 0;
                            height: 0;
                            border-width: 10rpx;
                            border-style: solid;
                            border-color: #060607 transparent transparent transparent;
                            top: 50rpx;
                            left: 50%;
                            margin-left: -8rpx;
                        }
                    }


                }
            }
        }
    }

    .cardItem {
        width: 100%;
        // height: 370upx;
        background-color: #fff;
        margin: 10upx auto;
        padding: 0 32upx;
        position: relative;
        padding-bottom: 18upx;

        .title {
            color: #333;
            font-weight: bold;

            padding-top: 28upx;
            padding-right: 120rpx;
        }

        .msg {
            padding-top: 20upx;
            color: #999999;

            text {
                padding-right: 30upx;
            }
        }

        .tags {
            display: flex;
            margin-top: 24upx;

            .tag {
                // width: 104upx;
                padding: 0 10upx;
                height: 42upx;
                line-height: 42upx;
                text-align: center;
                background-color: #F3FAFF;
                margin-right: 20upx;
            }
        }

        .hr {
            margin-top: 18upx;

            image {
                width: 72upx;
                height: 72upx;
                vertical-align: middle;
                margin-right: 10upx;
                border-radius: 50%;
            }
        }

        .salary {
            position: absolute;
            color: #3f6bb0;
            top: 28upx;
            right: 36upx;
        }

        .editLine {
            display: flex;
            justify-content: space-between;
            padding-top: 14upx;

            text {
                color: #999999;
            }

            .cancel {

                height: 52upx;
                line-height: 52upx;
                margin: 0;
                background-color: #F5F5F5;
            }
        }
    }

    .bar {
        width: 100%;
        // height: 116upx;
        background: #FFFFFF;
        position: fixed;
        bottom: 0;
        box-shadow: 0px -10px 60px rgba(162, 162, 162, 0.16);
        opacity: 1;

        .btns {
            width: 100%;
            height: 116upx;
            display: flex;
            align-items: center;
            padding: 0 30rpx;

            .more {
                display: flex;

                image {
                    width: 48upx;
                    height: 48upx;
                    margin-left: 20upx;
                }

                .send {
                    width: 100upx;
                    height: 48upx;
                    background: linear-gradient(180deg, #3465B1 0%, #789AD1 100%);
                    border-radius: 8upx;
                    color: #FFFFFF;
                    text-align: center;
                    line-height: 48upx;
                    margin-left: 15upx;
                }
            }

            .words {
                width: 100upx;
                height: 48upx;
                text-align: center;
                line-height: 48upx;
                background: linear-gradient(180deg, #3465B1 0%, #789AD1 100%);
                opacity: 1;
                border-radius: 8upx;
                color: #FFFFFF;
            }

            .putIn {
                margin-left: 20upx;
                color: #333;
                flex: 1;
                height: 100%;
            }
        }

        .express {
            width: 100%;
            padding: 0 48upx;
            height: 336upx;
            overflow-x: hidden;

            .all {
                font-weight: bold;
            }

            .emojis {
                width: 100%;
                display: grid;
                grid-template-columns: repeat(7, 1fr);

                .emoji {
                    font-size: 42upx;
                    text-align: center;
                    padding: 25upx 0;

                }
            }
        }

        .addFuncs {
            width: 100%;
            padding: 48upx;
            background: #FBFBFB;
            display: flex;
            height: 336upx;

            .fun {
                width: 96upx;
                height: 96upx;
                margin-right: 52upx;

                .name {
                    width: 100%;
                    text-align: center;
                }

                image {
                    width: 96upx;
                    height: 96upx;
                }
            }

        }
    }
</style>
